package cn.bigfire.wzdj.util.sign;

import cn.bigfire.wzdj.pojo.httpVo.HttpLoginResult;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.ThrowableUtil;
import net.dongliu.requests.Requests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class WZDJWXSign {

    private static final Logger log = LoggerFactory.getLogger(WZDJWXSign.class);

    public static HttpLoginResult loginByWxCode(String code){
        try {
            //body
            String openAppId = "wx71702c33334e92bd";//小程序 王者对决唯一
            LinkedHashMap<String,Object> bodyMap = new LinkedHashMap<>();
            bodyMap.put("openAppId",openAppId);
            bodyMap.put("userType",105);
            bodyMap.put("token",code);
            bodyMap.put("formAdID","");
            bodyMap.put("fromRSID","");
            TreeMap<String,Object> adInfoMap = new TreeMap<>();
            adInfoMap.put("pid", 2074010);
            bodyMap.put("adInfo", JSON.toJSONString(adInfoMap));
            bodyMap.put("adCache","");
            //参数
            String timestamp = (System.currentTimeMillis() / 1000)+"";
            String uuid = "wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM";//用户wx- openId
            TreeMap<String,String> paramMap = new TreeMap<>();
            paramMap.put("appId","2074");
            paramMap.put("pid","2074010");
            paramMap.put("clientType","5");
            paramMap.put("encryptflag","0");
            paramMap.put("timestamp", timestamp);
            paramMap.put("uuid",uuid);
            paramMap.put("version", "v2");
            paramMap.put("subUserType", "1051");
            //参数key转小写
            paramMap = lowerCaseMap(paramMap);
            //sign
            TreeMap<String,String> signMap = new TreeMap<>(paramMap);
            signMap.put("body", JSON.toJSONString(bodyMap));
            String sign = sign(signMap);
            //sign 重新放回参数中
            paramMap.put("sign", sign);
            //请求头
            HashMap<String,String> headers = new HashMap<>();
            headers.put("Host","sdkapi.hnys68.cn");
            headers.put("xweb_xhr","1");
            headers.put("Content-Type","application/json");
            headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c11)XWEB/11275");
            headers.put("Referer","https://servicewechat.com/wx71702c33334e92bd/13/page-frame.html");
            headers.put("Accept-Encoding","gzip, deflate, br");
            headers.put("Accept-Language","zh-CN,zh;q=0.9");
            headers.put("Accept", "*/*");
            //url参数，请求头，请求body，一把梭。发请求
            String wxLoginApi = "https://sdkapi.hnys68.cn/api/sdk/v2/accounts/action/registerlogin/openuser-mp";
            log.info("wxLoginApi:{}", wxLoginApi);
            log.info("param:{}", JSON.toJSONString(paramMap));
            log.info("body:{}", JSON.toJSONString(bodyMap));
            String readToText = Requests.post(wxLoginApi).params(paramMap).headers(headers).body(JSON.toJSONString(bodyMap)).send().readToText();
            log.info("result:{}", readToText);
            if (JSONUtil.isTypeJSONObject(readToText)) {
                return JSON.parseObject(readToText, HttpLoginResult.class);
            } else {
                log.error(readToText);
            }
        } catch (Exception e) {
            log.error("loginByWxCode has error:" + ThrowableUtil.stackTraceToString(e));
        }
        return null;
    }

    //签名，（排序，拼接，sha256）
    public static String SECRET_KEY = "d01474ee9670540687a7f2464a570abc";//不变key
    public static String sign(TreeMap<String,String> signMap){
        String signStr = MapUtil.sortJoin(signMap, "&", "=", true);
        log.info("signStr:{}",signStr);
        return SecureUtil.hmacSha256(SECRET_KEY).digestHex(signStr);
    }

    //map，key统一转换成小写
    private static TreeMap<String,String> lowerCaseMap(Map<String,String> originalMap){
        TreeMap<String, String> lowerCaseMap = new TreeMap<>();
        for (Map.Entry<String, String> entry : originalMap.entrySet()) {
            lowerCaseMap.put(entry.getKey().toLowerCase(), entry.getValue());
        }
        return lowerCaseMap;
    }



}
